package com.fourforfo.fourmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.fourforfo.common.to.es.SkuEsModel;
import com.fourforfo.fourmall.search.config.FourmallElasticSearchConfig;
import com.fourforfo.fourmall.search.constant.EsConstant;
import com.fourforfo.fourmall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service("productSaveService")
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    /**
     * 接受skuEsModels，将数据保存到ElasticSearch
     * @param skuEsModels
     * @return
     */
    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException{
//        restHighLevelClient;
        //1. 给es中建立索引，product，建立好映射关系
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            //构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            //将skuId作为唯一"_id"
            indexRequest.id(skuEsModel.getSkuId().toString());
            String skuEsModelString = JSON.toJSONString(skuEsModel);
            indexRequest.source(skuEsModelString, XContentType.JSON);

            bulkRequest.add(indexRequest);
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, FourmallElasticSearchConfig.COMMON_OPTIONS);

        //TODO 处理错误
        if(bulk.hasFailures()){
            List<String> collect = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
            log.error("商品上架提交数据到ElasticSearch发生错误，错误id：{},返回数据：{}",collect,bulk.toString());
            return false;
        }
        return true;


    }
}
